#!/bin/bash

# 日志文件路径
LOG_FILE="/var/log/auth.log"


# 发送告警到钉钉
WEBHOOK_URL="https://oapi.dingtalk.com/robot/send?access_token=you_token"
# 关键词（用于检测登录失败）
KEYWORD="pam_unix(sshd:auth): authentication failure"

# 监控日志文件，实时查找关键词
tail -Fn0 "$LOG_FILE" | while read line ; do
    echo "$line" | grep "$KEYWORD" &> /dev/null
    if [ $? = 0 ]
    then
        # 发现关键词，提取相关信息
        IP=$(echo "$line" | awk '{for(i=1;i<=NF;i++){if($i ~ /rhost=/){print $i}}}' | cut -d '=' -f 2)
        USER=$(echo "$line" | awk '{for(i=1;i<=NF;i++){if($i ~ /^user=/){print $i}}}' |cut -d '=' -f 2)
        # 查询IP的归属地信息
        location=$(curl -s ipinfo.io/$IP | jq -r '" Country: \(.country), City: \(.city), Region: \(.region)"')
        sleep 5
        # 构建消息内容

    PAYLOAD=$(cat <<-EOF
{       
"msgtype": "markdown",
"markdown": {
"title":"监控报警:异常登录",
"text":"
##### Linux服务器监控报警:异常登录 \n
>  ##### <font color=#67C23A> 【登录用户】</font> :<font color=#FF0000> $USER</font>
>  ##### <font color=#67C23A> 【登录IP】</font> :<font color=#FF0000> $IP </font> 
>  ##### <font color=#67C23A> 【IP归属地】</font> :<font color=#FF0000> $location </font> 
>  ##### <font color=#67C23A> 【告警时间】</font> :<font color=#FF0000> $(date +"%Y-%m-%d %H:%M:%S") </font> 
"
}
}
EOF
    )        
        # 发送通知到钉钉
        curl -s -H "Content-Type: application/json" -d "$PAYLOAD" "$WEBHOOK_URL" &>/dev/null

        # 可选：发送完成后打印日志
        echo "已发送通知"
    fi
done
